package com.usian.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usian.admin.mapper.AdUserMapper;
import com.usian.admin.model.admin.dtos.AdUserDto;
import com.usian.admin.model.admin.pojos.AdUser;
import com.usian.admin.model.common.dtos.ResponseResult;
import com.usian.admin.model.common.enums.AppHttpCodeEnum;
import com.usian.admin.service.UserLoginService;
import com.usian.admin.utils.common.AppJwtUtil;
import com.usian.base.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
@Service
public class UserLoginServiceImpl extends BaseServiceImpl<AdUserMapper, AdUser> implements UserLoginService {
    @Override
    public ResponseResult login(AdUserDto dto) {
        if (dto==null|| StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword()))return paramError;
        //AdUser user = baseMapper.selectOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()));
        AdUser one = getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, dto.getName()), true);
        if (one==null)return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"用户不存在");
        String s = DigestUtils.md5DigestAsHex((dto.getPassword() + one.getSalt()).getBytes());
        if (s.equals(one.getPassword())){
            one.setPassword("");
            one.setSalt("");
            String token = AppJwtUtil.getToken(one.getId().longValue());
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("user",one);
            hashMap.put("token",token);
            return ResponseResult.okResult(hashMap);
        }else return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"用户不存在");
    }

//    public static void main(String[] args) {
//        String s = DigestUtils.md5DigestAsHex(("123" + "666").getBytes());
//        System.out.println(s);
//    }
}
